package com.globallogic.vkulyk.JaxbHandler;

import java.io.File;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class JaxbHandler {
	Object object = null;

	public void marshallToXMLFile(Object object, String xmlFile)
			throws JAXBException {
		this.object = object;
		Marshaller marshaller = createMarshaller();
		marshaller.marshal(object, new File(xmlFile));
	}

	public String marshallToXMLString(Object object) throws JAXBException {
		this.object = object;
		Marshaller marshaller = createMarshaller();
		StringWriter stringWriter = new StringWriter();
		marshaller.marshal(object, stringWriter);
		return stringWriter.toString();
	}

	public void unmarshallFromXMLFile(Object object, String xmlFile)
			throws JAXBException {
		Marshaller marshaller = createMarshaller();
		marshaller.marshal(object, new File(xmlFile));
	}

	private Marshaller createMarshaller() throws JAXBException {
		//JAXBContext context = JAXBContext.newInstance(Catalog.class);
		JAXBContext context = JAXBContext.newInstance(object.getClass());
		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		return marshaller;
	}

	private void createUnmarshaller() {
		//Unmarshaller unmarshaller = context.createUnmarshaller();
		//Bookstore bookstore2 = (Bookstore) unmarshaller.unmarshal(new FileReader(
		//		BOOKSTORE_XML));
	}

}
